package com.gzu.finalwork.admin.service;

import com.gzu.finalwork.admin.mapper.EmailSettingsMapper;
import com.gzu.finalwork.entity.admin.EmailSettings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.Socket;
import java.io.IOException;

/**
 * 邮件设置服务类
 */
@Slf4j
@Service
public class EmailSettingsService {

    @Autowired
    private EmailSettingsMapper emailSettingsMapper;

    /**
     * 获取邮件设置
     */
    public EmailSettings getEmailSettings() {
        return emailSettingsMapper.selectEmailSettings();
    }

    /**
     * 更新邮件设置
     */
    public void updateEmailSettings(EmailSettings emailSettings) {
        emailSettingsMapper.updateEmailSettings(emailSettings);
    }

    /**
     * 测试邮箱连接
     */
    public boolean testEmailConnection(EmailSettings emailSettings) {
        try {
            // 参数验证
            if (emailSettings.getSmtpServer() == null || emailSettings.getSmtpServer().trim().isEmpty()) {
                log.error("SMTP服务器地址不能为空");
                return false;
            }
            if (emailSettings.getSmtpPort() == null || emailSettings.getSmtpPort() <= 0) {
                log.error("SMTP端口号无效");
                return false;
            }

            // 测试Socket连接到SMTP服务器
            try (Socket socket = new Socket()) {
                socket.connect(new java.net.InetSocketAddress(emailSettings.getSmtpServer(), emailSettings.getSmtpPort()), 5000);
                log.info("SMTP服务器连接测试成功：{}:{}", emailSettings.getSmtpServer(), emailSettings.getSmtpPort());
                return true;
            } catch (IOException e) {
                log.error("SMTP服务器连接失败：{}:{} - {}", emailSettings.getSmtpServer(), emailSettings.getSmtpPort(), e.getMessage());
                return false;
            }
            
        } catch (Exception e) {
            log.error("邮箱连接测试异常：", e);
            return false;
        }
    }
} 